<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 *
 *
 */
class Pricelist extends CI_Model  {
	/**
	 * Constructor
	 * @access protected
	 */
	function _construct()
	{
		// Call the Model constructor
		parent::_construct();
	}
	function getList($type,$id)
	{
		$responce=array();
		$responce['list']='';
		$responce['name']='';
		$responce['type']=$type;
		$query="select name from service where id=".$id;
		$result=$this->db->query($query);
		if($result->num_rows()>0)
		{
			$responce['name']=$result->row()->name;
		}
		$query="Select id,Name,`desc` from listoftables where idService=".$id;
		$result=$this->db->query($query);
		
		foreach($result->result() as $row)
		{
			$responce['list'][$row->id]['name']=$row->Name;
			$responce['list'][$row->id]['desc']=$row->desc;
		}
		$this->db->close();
		return $responce;
	}
	function showAllTables($type)
	{
		$query='select id,name from service where idType='.$type." and idUser=".$this->session->userdata('idUser');
		$this->log($query);
		$result=$this->db->query($query);
		$responce=array();
		$i=0;
		foreach($result->result() as $row)
		{
			$responce[$i]['name']=$row->name;
			$query='select id,name from listoftables where idService='.$row->id;
			$this->log($query);
			$tables=$this->db->query($query);
			$j=0;
			foreach($tables->result() as $table)
			{
				$responce[$i]['tables'][$j]['id']=$table->id;
				$responce[$i]['tables'][$j]['name']=$table->name;
				$j++;
			}
			$i++;
		}
		return json_encode($responce);
	}
	function getPrice($y,$m,$id)
	{
		$n=($m!=2?(($m%2)^($m>7))+30:(!($y%400)||!($y%4)&&($y%25)?29:28));
		$dateS=$y."-".$m."-01";
		$dateE=$y."-".$m."-".$n;

	
		$query="Select idStruct,idService from listoftables where id=".$id;
		$result=$this->db->query($query);
		if($result->num_rows()>0)
		{
			$idstruct=$result->row()->idStruct;
			$idServ=$result->row()->idService;
		}
		else{$this->log('getPrice Error table id='.$id);return false;}
		$query="Select idrow from liststruct where idStruct=".$idstruct." order by id desc";
		$result=$this->db->query($query);
		$i=0;
		foreach($result->result() as $row)
		{
			$query="Select id,name from rows where id=".$row->idrow;
			$rowsName=$this->db->query($query);
			if($rowsName->num_rows()>0)
			{
				$row=$rowsName->row();
				$struct[$i]['id']=$row->id;
				$struct[$i]['name']=$row->name;
				$i++;
			}
		}
		$query="Select `Date`,`price`,`idRow` from price where idTable=".$id." and `date`>='$dateS' and `date`<='$dateE'";
		$this->log($query);
		$result=$this->db->query($query);
		$i=0;
		$DATA=array();
		$i=0;
		foreach($result->result() as $row)
		{
			$DATA[$i]['price']=$row->price;
			$DATA[$i]['date']=$row->Date;
			$DATA[$i]['idRow']=$row->idRow;
			$i++;
		}
		$responce->page = 1;
		$responce->total = 1;
		$responce->records = count($struct);
		$nacenka=array();
		if($this->session->userdata('userType')==0)
		{
			$query="select 
						`date`,
						price,
						type,
						idRow
					from agentprice 
							where 
							userId=".$this->session->userdata('idUser')." 
								and `date`>='".$dateS."' 
								and idService=".$idServ." 
								and `date`<='".$dateE."'";
			//print_r($query);
			$nacenkaQuery=$this->db->query($query);
			
				foreach ($nacenkaQuery->result() as $row)
				{
					$nacenka[$row->idRow][$row->date]['price']=$row->price;
					$nacenka[$row->idRow][$row->date]['type']=$row->type;
					
				}
			
		}
		for($i=0;$i<count($struct);$i++)
		{
			$rows[$i]['cell']=array($struct[$i]['id'],$struct[$i]['name']);
			for($j=2;$j<=$n+1;$j++)
			{
				if($price=$this->_search($j-1,$m,$y,$struct[$i]['id'],$DATA))
				{
					$rows[$i]['cell'][$j]=$price==0?"":$price;
					if($this->session->userdata('userType')==0)
					{
						$mdate=$y.'-'.$m.'-';
							
						if(strlen ($j-1)<2)
						{
							$mdate.='0'.($j-1);
						}
						else
						{
							$mdate.=$j-1;
						}
						if(isset($nacenka[$struct[$i]['id']][$mdate])&&$rows[$i]['cell'][$j]!=0)
						{
							
							$this->log($nacenka[$struct[$i]['id']][$mdate]);
							if($nacenka[$struct[$i]['id']][$mdate]['type']==0)
							{
								$rows[$i]['cell'][$j]+=$nacenka[$struct[$i]['id']][$mdate]['price'];
							}
							else
							{
								$rows[$i]['cell'][$j]+=$rows[$i]['cell'][$j]*($nacenka[$struct[$i]['id']][$mdate]['price'])/100;
							}
						}
					}
					
				}
				else
				{
					$rows[$i]['cell'][$j]="";
				}
			}
		}
		$responce->rows=$rows;
		$this->db->close();
		return json_encode($responce);
	}
	function edit($idtable,$idrow,$days,$year,$month)
	{
		
		$date=$year."-".$month."-";

		foreach($days as $day=>$price)
		{
				$intDay=substr($day, 1);
				$query="Select id from price where date='".$date.$intDay."' and idTable=".$idtable." and idRow=".$idrow;
				$result=$this->db->query($query);
				if($result->num_rows()>0)
				{
					$query="Update `price` SET  `price` =  ".$price." WHERE `id` = ".$result->row()->id;

					$this->db->query($query);
				}
				else
				{
					if($price!=0)
					{
						$query="insert into price (idTable,idRow,`date`,`price`) values ('".$idtable."','$idrow','".$date.$intDay."','".$price."')";
						$this->db->query($query);
						$this->db->close();
					}
				}
		}
	}
	function _search($dd,$mm,$yyyy,$idRow,$DATA)
	{
		$date=$yyyy;
		if (strlen ($mm)<2) {
			$date.="-0".$mm;
		}
		else
		{
			$date.="-".$mm;
		}
		if (strlen ($dd)<2) {
			$date.="-0".$dd;
		}
		else
		{
			$date.="-".$dd;
		}
		for ($i=0;$i<count($DATA);$i++)
		{
			if(strcmp ($DATA[$i]['date'],$date)==0&&$DATA[$i]['idRow']==$idRow)//
			{
				return $DATA[$i]['price'];
			}
		}
		return false;
	}
	function  getRowList()
	{
		
		$query='Select id,name from rows';
		$result=$this->db->query($query);
		$responce="<div id='n'><div class='row'><table ><tr><td><select name='n[price][1]'>";
		foreach($result->result() as $row)
		{
			$responce.="<option value=".$row->id.">".$row->name."</option>";
		}
		$responce.="</select></td><td> <div class='ui-icon ui-icon-plus' width=16 height=16 num='1' onClick='addRowlist(\"n\");'>+</div></td><td class='rowT'></td></tr></table></div></div>";
		return $responce;
	}
	function getRowListToCalendar($idServ)
	{
		
		$query="Select idStruct from listoftables where idService=".$idServ." limit 1";
		$result=$this->db->query($query);
		$responce=array();
		if($result->num_rows()>0)
		{
			$query="Select idrow from liststruct where idstruct=".$result->row()->idStruct;

			$result=$this->db->query($query);
			foreach($result->result() as $row)
			{
				$query="Select name from rows where id=".$row->idrow;
				$res=$this->db->query($query);
				if($res->num_rows()>0)
				{
					$responce[]="<tr><td>".$res->row()->name."</td><td><input type=text name=r[".$row->idrow."]></td></tr>";
				}
			}
		}
		return implode('',$responce);
	}
	function addTableInService($idServ,$name,$desc,$rows)
	{
	
		/*$query="Select id from listoftables where idService=".$idServ;
		$result=$this->db->query($query);
		if($result->num_rows()>0)
		{
			return false;
		}*/
		$query="select idStruct from liststruct order by idStruct desc limit 1";
		$result=$this->db->query($query);
		$structId=1;
		if($result->num_rows()>0)
		{
			$structId=(int)($result->row()->idStruct)+1;
		}
		foreach($rows as $row)
		{
			$query="Insert into liststruct (idStruct,idRow) values ($structId,$row)";
			$this->log($query);
			$this->db->query($query);
		}
		$query="Insert into listoftables (idService,name,`desc`,idStruct) values ($idServ,'$name','$desc',$structId)";
		$this->db->query($query);
		$query="Select id from listoftables where idService=$idServ and idStruct=$structId";
		$result=$this->db->query($query);
		if($result->num_rows>0)
		{
			$key=$result->row()->id;
		}

		return '<tr >
						<td width="2%"> &nbsp;</td>
						<td><h2>'.$name.'</h2> '.$desc.'</td>
						<td width="2%"> &nbsp;</td>
					</tr>
					<tr >
						<td width="2%"> &nbsp;</td>
						<td>
							<div id="pager'.$key.'"></div>
							<table id="table'.$key.'"></table>
							<script>tables.push('.$key.'); createTable("'.$key.'",2011,11);</script>

						</td>
						<td width="2%"> &nbsp;</td>
					</tr>';
	}
	function setprice($table,$dates,$rows,$skidka)
	{
		
		$date=explode(';',$dates);
		
			foreach($date as $day)
			{
	
				if((preg_match("/^(\d\d\d\d)-(\d|\d\d)-(\d|\d\d)/",$day)))
				{
					foreach($rows as $idRow => $price)
					{
						if($price!=0)
						{
							if($skidka==0)
							{
								$query="Select id from price where idtable=".$table." and idRow=".$idRow." and `date`='".$day."' ";
								$result=$this->db->query($query);
								if($result->num_rows>0)
								{
									$query="update price set price=".$price." where id=".$result->row()->id;
									$this->db->query($query);
								}
								else
								{
									$query="insert into price (`idtable`,`idrow`,`date`,`price`) values ($table,$idRow,'$day',$price)";
									$this->db->query($query);
								}
							}else
							{
								$query="Select `id`,`price` from price where idtable=".$table." and idRow=".$idRow." and `date`='".$day."' ";
								$result=$this->db->query($query);
								if($result->num_rows>0)
								{
									$query="update price set price=".($result->row()->price*((100-$price)/100))." where id=".$result->row()->id;
									$this->log($query);
									$this->db->query($query);
								}
							}
						}
					}
				}
			}
		}

function cloneTableInService($idServ, $name, $desc, $idTable)
	{
		$query="Select idStruct from listoftables where idService=".$idServ." and  id=".$idTable;
		$result=$this->db->query($query);
		if($result->num_rows()<0)
			return false;
		$idStruct = $result->row()->idStruct;
		$this->Log("Выбираем idStruct---".$idStruct);
		$query="insert into listoftables (name, `desc`, idStruct, idService)
				values ('".$name."','".$desc."',".$idStruct.",".$idServ.")";
		$this->Log("Выполняем запрос на внесение данных в listoftables----".$query);
		$this->db->query($query);
		$query="Select id from listoftables where idService=".$idServ." and idStruct=".$idStruct." and name='".$name."'";
		$result=$this->db->query($query);
		$this->Log("Выбираем id---".$result->row()->id);
		if($result->num_rows>0)
		{
			$key=$result->row()->id;
			$this->Log("Выбираем id---".$key);
		}

		return '<tr >
								<td width="2%"> &nbsp;</td>
								<td><h2>'.$name.'</h2> '.$desc.'</td>
								<td width="2%"> &nbsp;</td>
							</tr>
							<tr >
								<td width="2%"> &nbsp;</td>
								<td>
									<div id="pager'.$key.'"></div>
									<table id="table'.$key.'"></table>
									<script>tables.push('.$key.'); createTable("'.$key.'",2011,11);</script>

								</td>
								<td width="2%"> &nbsp;</td>
							</tr>';
	}
function deleteTableData ($idTable){
		$query = "delete from price where idTable=".$idTable;
		$this->Log("Удаление по запросу-----".$query);
		$result = $this->db->query($query);
		if ($result)
		$this->Log("Удаление прошло успешно-----".$query);
		else
		$this->Log("Удаление провалилось-----".$query);
	}
function deleteTable ($idTable){
		
		$query = "delete from price where idTable=".$idTable;
		$this->Log("Удаление по запросу-----".$query);
		$result = $this->db->query($query);
		if ($result)
		$this->Log("Удаление прошло успешно-----".$query);
		else
		$this->Log("Удаление провалилось-----".$query);

		$query = "delete from listoftables where id=".$idTable;
		$this->Log("Удаление по запросу-----".$query);
		$result = $this->db->query($query);
		if ($result)
		$this->Log("Удаление прошло успешно-----".$query);
		else
		$this->Log("Удаление провалилось-----".$query);
	}
function deleteTables ($idServ){
		
		$query = "delete from price where idTable in (select id from listoftables where idService=".$idServ.")";
		$this->Log("Удаление по запросу-----".$query);
		$result = $this->db->query($query);
		if ($result)
		$this->Log("Удаление прошло успешно-----".$query);
		else
		$this->Log("Удаление провалилось-----".$query);

		/*$query = "delete FROM liststruct where idStruct in (select  idStruct  from listoftables where idService=".$idServ.")";
		$this->Log("Удаление по запросу-----".$query);
		$result = $this->db->query($query);
		if ($result)
		$this->Log("Удаление прошло успешно-----".$query);
		else
		$this->Log("Удаление провалилось-----".$query);
		*/
		
		$query = "delete from listoftables where idService=".$idServ;
		$this->Log("Удаление по запросу-----".$query);
		$result = $this->db->query($query);
		if ($result)
		$this->Log("Удаление прошло успешно-----".$query);
		else
		$this->Log("Удаление провалилось-----".$query);
	}
function deleteTableDataByMonth ($idTable, $date){
		$query = "delete from price where idTable=".$idTable." and left(Date,7)='".$date."'";
		$this->Log("Удаление по запросу-----".$query);
		$result = $this->db->query($query);
		if ($result)
		$this->Log("Удаление прошло успешно-----".$query);
		else
		$this->Log("Удаление провалилось-----".$query);
	}
}